/**
 * ZHU framework. Copyright 2012-, all rights reserved.
 *
 * $Id: WebSessionContextListener.java 33 2012-08-30 08:10:18Z zhuxiaopeng $
 * $Revision: 33 $
 * $Date: 2012-08-30 16:10:18 +0800 (四, 2012-08-30) $
 * $Author: zhuxiaopeng $
 */
package zhu.framework.web.servlet;

import java.util.logging.*;

import javax.inject.*;
import javax.servlet.annotation.*;
import javax.servlet.http.*;

import zhu.framework.web.*;

/**
 * <p>
 * </p>
 * 
 * @author $Author: zhuxiaopeng $
 * @version $Revision: 33 $ - $Date: 2012-08-30 16:10:18 +0800 (四, 2012-08-30) $
 */
@WebListener
public final class WebSessionContextListener implements HttpSessionListener {
	public final static String WEB_SESSION_CONTEXT_KEY = "zhu.httpWebSessionContext";

	/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * javax.servlet.http.HttpSessionListener#sessionCreated(javax.servlet.http
	 * .HttpSessionEvent)
	 */
	@Override
	public void sessionCreated(final HttpSessionEvent se) {
		if (logger.isLoggable(Level.CONFIG)) {
			logger.config("An WebSessionContext is being created");
		}
		//
		final HttpSession session = se.getSession();
		final HttpWebSessionContext context = new HttpWebSessionContext(session);
		session.setAttribute(WEB_SESSION_CONTEXT_KEY, context);
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * javax.servlet.http.HttpSessionListener#sessionDestroyed(javax.servlet
	 * .http.HttpSessionEvent)
	 */
	@Override
	public void sessionDestroyed(final HttpSessionEvent se) {
		if (logger.isLoggable(Level.CONFIG)) {
			logger.config("An WebSessionContext is being destroyed");
		}
		//
		final HttpSession session = se.getSession();
		final WebSessionContext context = (WebSessionContext) session.getAttribute(WEB_SESSION_CONTEXT_KEY);
		if (context != null) {
			logger.fine(String.format("Destroying WebSessionContext : sessionId=%s", context.getId()));
			//
			session.removeAttribute(WEB_SESSION_CONTEXT_KEY);
			context.destroy();
		} else {
			logger.warning(String.format("No WebSessionContext has been associated with the HttpSession : ignore it : key=%s, sessionId=%s",
					WEB_SESSION_CONTEXT_KEY, session.getId()));
		}
	}

	@Inject
	private Logger logger;
}
